﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ufida.u9.ait.openapi.utils
{
    internal class HttpUtils
    {
        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string Get(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                request.UserAgent = null;
                //request.Timeout = Timeout;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();

                myStreamReader.Close();
                myResponseStream.Close();
                response.Close();

                return retString;
            }catch (Exception ex)
            {
                throw new Exception($"Get请求失败,URL[{url}],错误消息:{ex.Message}", ex);
            }
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data">body数据,一般是json格式</param>
        /// <returns></returns>
        public static string Post(string url, string data)
        {
            try
            {
                HttpWebRequest request = null;
                //如果是发送HTTPS请求  
                request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "POST";
                request.ContentType = "application/json";
                request.ContentLength = Encoding.UTF8.GetByteCount(data);

                //body写入json数据
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.UTF8))
                {
                    writer.Write(data);
                }

                HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;
                if (httpWebResponse == null)
                {
                    throw new Exception($"调用url[{url}]失败");
                }

                Stream responseStream = httpWebResponse.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                string retString = reader.ReadToEnd();

                reader.Close();
                responseStream.Close();
                httpWebResponse.Close();

                return retString;
            }catch(Exception ex)
            {
                throw new Exception($"Post请求失败,URL[{url}],错误消息:{ex.Message}", ex);
            }
        }

        /// <summary>
        /// 上传媒体文件
        /// </summary>
        /// <param name="url">上传媒体文件的微信公众平台接口地址</param>
        /// <param name="file">要上传的媒体文件对象</param>
        /// <returns>返回上传的响应结果，详情参看微信公众平台开发者接口文档</returns>
        public static string UploadPost(string url, string file)
        {
            string result = String.Empty;
            try
            {
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                byte[] responseArray = client.UploadFile(url, "POST", file);
                result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);
                Console.WriteLine("上传result:" + result);
            }
            catch (Exception ex)
            {
                //result = "Error:" + ex.Message;
                //Console.WriteLine("发送GET请求出现异常：" + ex.Message);
                throw new Exception($"上传文件失败,url[{url}],错误消息:{ex.Message}", ex);
            }
            return result;
        }

        /// <summary>
        /// 从URL下载文件,并存储到filePath
        /// </summary>
        /// <param name="url">文件下载URL</param>
        /// <param name="filePath">文件路径,含文件名</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static bool DownloadFile(string url, string filePath)
        {
            bool result = false;
            
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                //request.Accept = "*/*";
                //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                FileUtils.WriteFile(filePath, responseStream);
                responseStream.Close();
                response.Close();

                result = true;
            }
            catch (Exception ex)
            {
                throw new Exception($"下载文件失败,url[{url}],错误消息:{ex.Message}", ex);
            }
            return result;
        }
    }
}
